// base64字符串
function dataToFile(params) {
  let type = params.type
  let fileName = params.fileName
  let data = params.data;

  // 判断数据是否存在
  if(typeof data == 'string') {
    let bstr = window.atob(data)
    let n = bstr.length;
    let u8arr = Uint8Array(n);
    while(n--){
      u8arr[n] = bstr.charCodeAt(n)
    }
    let blob = new Blob([data], { type })

    const link = document.createElement('a')
    // 兼容 IE
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blob, fileName)
    } else {
      // 非IE 浏览器
      link.href = window.URL.createObjectURL(blob)
      link.download = fileName
    }
    link.click()
    window.URL.revokeObjectURL(link.href); // 释放内存
  }
}

// 二进制流下载
function dataFlowToFile(params) {
  let type = params.type
  let fileName = params.fileName
  let data = params.data;
    let blob = new Blob([data], { type })

    const link = document.createElement('a')
    // 兼容 IE
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blob, fileName)
    } else {
      // 非IE 浏览器
      link.href = window.URL.createObjectURL(blob)
      link.download = fileName
    }
    link.click()
    window.URL.revokeObjectURL(link.href); // 释放内存
}


function BlobToUrl(params) {
  let type = params.type
  let data = params.data;
  const url = window.URL.createObjectURL(new Blob([data], { type }))
  return url;    
}

export {
  dataToFile,
  dataFlowToFile,
  BlobToUrl
}